package com.xt.xxb.taobao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xt.xxb.Main;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TbApi {
    private final static String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36";

    /**
     * 卡券核销查询
     *
     * @param token
     * @param cookie
     * @param code
     * @return
     */
    private static TbResponse consumeCodeQry(String token, String cookie, String code) {
        mmstat(cookie, "https://ma.taobao.com/consume/code.htm");
        boolean needAuth = isNeedAuth(cookie);
        if (needAuth) {
            return TbResponse.fail("-1", "登录过期，请重新登录");
        }
        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("_tb_token_", token);
        //必须携带
        parameters.put("event_submit_do_validate_code", "%CC%E1%BD%BB");
        parameters.put("action", "consume/code_action");
        parameters.put("_fm.cod._0.co", code);
        parameters.put("_fm.cod._0.m", "");

        HashMap<String, String> headersMap = new HashMap<>();
        headersMap.put("authority", "ma.taobao.com");
        headersMap.put("method", "POST");
        headersMap.put("path", "/consume/code.htm");
        headersMap.put("scheme", "https");
        headersMap.put("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
        headersMap.put("accept-encoding", "gzip, deflate, br");
        headersMap.put("accept-language", "zh-CN,zh;q=0.9");
        headersMap.put("content-type", "application/x-www-form-urlencoded");
        headersMap.put("cookie", cookie);
        //referer 必须要带
        headersMap.put("referer", "https://ma.taobao.com/consume/code.htm");
        headersMap.put("origin", "https://ma.taobao.com");
        headersMap.put("user-agent", USER_AGENT);
        try {
            HttpResponse response = HttpClient.postForm("https://ma.taobao.com/consume/code.htm", parameters, headersMap);
            if (response == null) {
                return TbResponse.fail("-1", "渠道无响应");
            }
            String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (resp == null || resp.isEmpty()) {
                return TbResponse.fail("-1", "响应内容为空");
            }
            Document document = Jsoup.parse(resp);
            Elements form = document.getElementsByTag("form");
            Elements action = form.select("input[name='action']");
            String actionVal = action.val();
            boolean exists = "consume/confirm_action".equals(actionVal);
            if (!exists) {
                Element jConsumeMsg = document.getElementById("J_ConsumeMsg");
                if (jConsumeMsg == null || jConsumeMsg.text().isEmpty()) {
                    return TbResponse.fail("-1", "卡券不存在");
                }
                return TbResponse.fail("-1", jConsumeMsg.text());
            }
            //获取卡券数量
            Elements consumeNum = form.select("input[name='consumeNum']");
            String dataMax = consumeNum.attr("data-max");
            return TbResponse.success(dataMax);
        } catch (Exception e) {
            return TbResponse.fail("-1", "渠道请求异常");
        }
    }

    /**
     * 卡券核销
     *
     * @param cookie Cookie
     * @param code   验证码
     * @return
     */
    public static TbResponse consumeCode(String cookie, String code) {
        String token = getCookie("_tb_token_", cookie);
        if (token == null || token.isEmpty()) {
            return TbResponse.fail("-1", "_tb_token_不存在");
        }
        TbResponse response = consumeCodeQry(token, cookie, code);
        if (!response.isSuccess()) {
            return response;
        }
        Object data = response.getData();
        return consumeCodeConfirm(token, cookie, code, data + "");
    }

    /**
     * 卡券核销
     *
     * @param code
     * @param num
     * @return
     */
    private static TbResponse consumeCodeConfirm(String tbToken, String tbCookie, String code, String num) {
        mmstat(tbCookie, "https://ma.taobao.com/consume/code.htm");
        boolean needAuth = isNeedAuth(tbCookie);
        if (needAuth) {
            return TbResponse.fail("-1", "登录过期，请重新登录");
        }
        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("_tb_token_", tbToken);
        //必须携带
        parameters.put("event_submit_do_confirm", "%CC%E1%BD%BB");
        parameters.put("action", "consume/confirm_action");
        parameters.put("code", code);
        parameters.put("mobile", "");
        parameters.put("consumeNum", num);
        HashMap<String, String> headersMap = new HashMap<>();
        headersMap.put("authority", "ma.taobao.com");
        headersMap.put("method", "POST");
        headersMap.put("path", "/consume/code.htm");
        headersMap.put("scheme", "https");
        headersMap.put("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
        headersMap.put("accept-encoding", "gzip, deflate, br");
        headersMap.put("accept-language", "zh-CN,zh;q=0.9");
        headersMap.put("content-type", "application/x-www-form-urlencoded");
        headersMap.put("cookie", tbCookie);
        //referer 必须要带
        headersMap.put("referer", "https://ma.taobao.com/consume/code.htm");
        headersMap.put("origin", "https://ma.taobao.com");
        headersMap.put("user-agent", USER_AGENT);
        try {
            HttpResponse response = HttpClient.postForm("https://ma.taobao.com/consume/code.htm", parameters, headersMap);
            if (response == null) {
                return TbResponse.fail("-1", "渠道无响应");
            }
            int statusCode = response.getStatusLine().getStatusCode();
            String redirectUrl = null;
            if (statusCode == 302) {
                redirectUrl = response.getLastHeader("Location").getValue();
                response = HttpClient.get(redirectUrl, headersMap);
            }
            if (redirectUrl != null && (redirectUrl.startsWith("https://ma.taobao.com/consume/success.htm") || redirectUrl.contains("/success.htm"))) {
                return TbResponse.success();
            }
            String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (resp == null || resp.isEmpty()) {
                return TbResponse.fail("-1", "响应内容为空");
            }
            Document document = Jsoup.parse(resp);
            Element jConsumeMsg = document.getElementById("J_ConsumeMsg");
            if (jConsumeMsg == null || jConsumeMsg.text().isEmpty()) {
                return TbResponse.fail("-1", "卡券核销失败");
            }
            return TbResponse.fail("-1", jConsumeMsg.text());
        } catch (Exception e) {
            return TbResponse.fail("-1", "渠道请求异常");
        }
    }

    /**
     * 订单查询
     *
     * @param cookie
     * @return
     */
    public static boolean isNeedRelogin(String cookie) {
        mmstat(cookie, "https://trade.taobao.com/trade/itemlist/list_sold_items.htm?spm=a2142.3063657.category.d28.143e1a43QU21vx&mytmenu=ymbb");
        return isNeedAuth(cookie);
    }

    public static TbResponse orderQuery(String cookie, String orderId) {
        if (orderId == null || orderId.isEmpty()) {
            return TbResponse.fail("-1", "订单号不能为空");
        }
        mmstat(cookie, "https://trade.taobao.com/trade/itemlist/list_sold_items.htm?spm=a2142.3063657.category.d28.143e1a43QU21vx&mytmenu=ymbb");
        boolean needAuth = isNeedAuth(cookie);
        if (needAuth) {
            return TbResponse.fail("-1", "登录过期，请重新登录");
        }
        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("pageNum", "1");
        parameters.put("pageSize", "15");
        parameters.put("auctionType", "0");
        parameters.put("close", "0");
        parameters.put("queryMore", "true");
        parameters.put("rxAuditFlag", "0");
        parameters.put("rxElectronicAllFlag", "0");
        parameters.put("rxElectronicAuditFlag", "0");
        parameters.put("rxHasSendFlag", "0");
        parameters.put("rxOldFlag", "0");
        parameters.put("rxSendFlag", "0");
        parameters.put("rxSuccessflag", "0");
        parameters.put("rxWaitSendflag", "0");
        parameters.put("tradeTag", "0");
        parameters.put("useCheckcode", "false");
        parameters.put("useOrderInfo", "false");
        parameters.put("errorCheckcode", "false");
        parameters.put("action", "itemlist/SoldQueryAction");
        parameters.put("orderId", orderId);
        parameters.put("prePageNo", "1");
        parameters.put("buyerNick", "");
        parameters.put("dateBegin", "0");
        parameters.put("dateEnd", "0");
        parameters.put("logisticsService", "");
        parameters.put("orderStatus", "");
        parameters.put("queryOrder", "desc");
        parameters.put("rateStatus", "");
        parameters.put("refund", "");
        parameters.put("sellerNick", "");
        parameters.put("tabCode", "latest3Months");

        HashMap<String, String> headersMap = new HashMap<>();
        headersMap.put("authority", "trade.taobao.com");
        headersMap.put("method", "POST");
        headersMap.put("path", "/trade/itemlist/asyncSold.htm?event_submit_do_query=1&_input_charset=utf8");
        headersMap.put("scheme", "https");
        headersMap.put("accept", "application/json, text/javascript, */*; q=0.01");
        headersMap.put("accept-encoding", "gzip, deflate, br");
        headersMap.put("accept-language", "zh-CN,zh;q=0.9");
        headersMap.put("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        headersMap.put("cookie", cookie);
        //referer 必须要带
        headersMap.put("referer", "https://trade.taobao.com/trade/itemlist/list_sold_items.htm?spm=a2142.3063657.category.d28.143e1a43QU21vx&mytmenu=ymbb");
        headersMap.put("user-agent", USER_AGENT);
        try {
            HttpResponse response = HttpClient.postForm("https://trade.taobao.com/trade/itemlist/asyncSold.htm?event_submit_do_query=1&_input_charset=utf8", parameters, headersMap);
            String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (resp == null || resp.isEmpty()) {
                return TbResponse.fail("-1", "响应内容为空");
            }
            JSONObject respJson = JSONObject.parseObject(resp);
            JSONArray mainOrders = respJson.getJSONArray("mainOrders");
            if (mainOrders == null || mainOrders.isEmpty()) {
                return TbResponse.fail("-1", String.format("订单不存在[%s]", orderId));
            }
            return TbResponse.success(mainOrders.getJSONObject(0));
        } catch (Exception e) {
            e.printStackTrace();
            return TbResponse.fail("-1", "渠道请求异常");
        }
    }

    /**
     * 查询前置请求2/3
     *
     * @param cookie
     * @return
     */
    public static boolean isNeedAuth(String cookie) {
        HashMap<String, String> headersMap = new HashMap<>();
        headersMap.put("cookie", cookie);
        headersMap.put("referer", "https://trade.taobao.com/trade/itemlist/list_sold_items.htm?spm=a2142.3063657.category.d28.143e1a43QU21vx&mytmenu=ymbb");
        headersMap.put("user-agent", USER_AGENT);
        try {
            HttpResponse response = HttpClient.get(String.format("https://trade.taobao.com/trade/security/auth_user_info.htm?_ksTS=%s_%s", Calendar.getInstance().getTimeInMillis(), 262), headersMap);
            String text = EntityUtils.toString(response.getEntity(), "GBK");
            if (text == null || text.isEmpty()) {
                return false;
            }
            if (!text.contains("isNeedAuth")) {
                return true;
            }
            JSONObject jsonObject = JSON.parseObject(text);
            Boolean isNeedAuth = jsonObject.getBoolean("isNeedAuth");
            if (isNeedAuth == null) {
                return true;
            }
            return isNeedAuth;
        } catch (Exception e) {
            return false;
        }
    }

    private static void mmstat(String cookie, String target) {
        HashMap<String, String> headersMap = new HashMap<>();
        headersMap.put("cookie", cookie);
        headersMap.put("User-Agent", USER_AGENT);
        headersMap.put("Referer", target);
        try {
            String url = String.format("https://go.mmstat.com/tbapp.1002.1.3?t=%s&url=%s", Calendar.getInstance().getTimeInMillis(), target);
            HttpClient.get(url, headersMap);
        } catch (Exception ignore) {
        }
    }

    private static final int CONNECT_CNT_MAX = 3;
    private static final int CONNECT_TIME_SPLIT = 60 * 1000;
    private static final String NOTIFY_URL = "";

    /**
     * 支付回调
     */
    public static void transNotify(String orderId, int amount) {
        JSONObject body = new JSONObject();
        body.put("out_trade_no", orderId);
        body.put("amount", amount);
        ThreadPoolUtils.execute(() -> {
            try {
                boolean flag = false;
                for (int cnt = 0; cnt < CONNECT_CNT_MAX; cnt++) {
                    HttpResponse httpResponse = HttpClient.postJson(NOTIFY_URL, body);
                    HttpEntity entity = httpResponse.getEntity();
                    if (entity != null) {
                        String result = EntityUtils.toString(entity);
                        if (result != null && !result.isEmpty() && "success".equalsIgnoreCase(result)) {
                            Main.logger("通知下发成功,body={}");
                            flag = true;
                            break;
                        }
                    }
                    Thread.sleep(CONNECT_TIME_SPLIT);
                }
                if (!flag) {
                    Main.logger("通知下发失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 解析cookie
     *
     * @param cookie
     * @return
     */
    public static String getCookie(String target, String cookie) {
        if (cookie == null || cookie.isEmpty()) {
            return null;
        }
        String[] keys = cookie.split(";");
        for (String item : keys) {
            String[] kv = item.split("=");
            if (kv.length >= 2) {
                String key = kv[0].trim();
                if (target.equals(key)) {
                    return kv[1];
                }
            }
        }
        return null;
    }

    private final static String PATTERN_UNICODE = "(\\\\u(\\p{XDigit}{4}))";

    /**
     * 解析昵称 unicode->中文
     *
     * @param src
     * @return
     */
    private static String decode(String src) {
        try {
            src = URLDecoder.decode(src, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return src;
        }
        Pattern pattern = Pattern.compile(PATTERN_UNICODE);
        Matcher matcher = pattern.matcher(src);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            src = src.replace(matcher.group(1), ch + "");
        }
        return src;
    }

    public static void main(String[] args) {
        String cookies = "thw=cn; x=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0%26__ll%3D-1%26_ato%3D0; hng=CN%7Czh-CN%7CCNY%7C156; enc=D8pJTGTHg1MMyVSVXr6AVK2O%2FWY4fLMKmwMNoRgJs7aubor1buhpsB6Pj2WElnwBy1kciZ5sABarVzG5%2FrfTcTIB7TZ8iACgS2qcgq%2BQVjo%3D; UM_distinctid=171a561f5bb76-08274376783c09-5313f6f-e1000-171a561f5bc76; t=c1be8ae2e1a9231aefe72180f3a0437e; _m_h5_tk=dea6f277fd470ff012bc721c3e47b75d_1589517434209; _m_h5_tk_enc=d5dbb55610f192efe6d7ba530f1c6284; cookie2=16f9bf05a2e13363b5fbe4fab9da41cc; _tb_token_=79e3a13899b9; _samesite_flag_=true; v=0; cna=sUHDFaFvSksCAToXP+lvIcHR; tfstk=cXK1Bdv9E5V6IdxaYIMFutGpHSsVZ8gCpV1eCe4zO9agZnp1itZPN9yMoWZdy91..; sgcookie=Ehj2yiixcqNI1Ytr0Jh2k; unb=2805422229; uc3=vt3=F8dBxGZrX5ls11hf8wA%3D&nk2=tZeg5DYKdklryA%3D%3D&lg2=URm48syIIVrSKA%3D%3D&id2=UUBYgbP%2Fj3plJg%3D%3D; csg=0c2911b8; lgc=%5Cu5468%5Cu5468%5Cu5468%5Cu5A77%5Cu5440; cookie17=UUBYgbP%2Fj3plJg%3D%3D; dnk=%5Cu5468%5Cu5468%5Cu5468%5Cu5A77%5Cu5440; skt=13a2441913ab12dd; existShop=MTU4OTUxMDk0Nw%3D%3D; uc4=nk4=0%40tyORzivMizi0rl2wUboLaWM2ljEP&id4=0%40U2LK%2FAlRTu7HbKtNWQnmQZOVbX45; tracknick=%5Cu5468%5Cu5468%5Cu5468%5Cu5A77%5Cu5440; _cc_=WqG3DMC9EA%3D%3D; _l_g_=Ug%3D%3D; sg=%E5%91%809b; _nk_=%5Cu5468%5Cu5468%5Cu5468%5Cu5A77%5Cu5440; cookie1=B0P%2FhpCxWjXnXb15lFqcYRLDQCOrzJn63HIOMwEJa1s%3D; mt=ci=120_1; uc1=cookie14=UoTUM2U4HoQ%2FPQ%3D%3D&cookie16=Vq8l%2BKCLySLZMFWHxqs8fwqnEw%3D%3D&existShop=false&cookie21=WqG3DMC9Fb5mPLIQo9kR&cookie15=UIHiLt3xD8xYTw%3D%3D&pas=0; l=eBTQxbLnQC2WtX8XBO5Bhurza779rBAXcdFzaNbMiInca17dip_vCNQc8NTBrdtxgtCbrF-PijrhsRUD8UUd0WPP3SsLrSY_rxJO.; isg=BGFhUktIm45oQjf6MPzJabiscC17DtUAAQM1fMMwGWhnKpH8DF9p0J0sjV6soW04";
        cookies = "_l_g_=Ug%3D%3D; lgc=%5Cu5468%5Cu5468%5Cu5468%5Cu5A77%5Cu5440; cookie1=B0P%2FhpCxWjXnXb15lFqcYRLDQCOrzJn63HIOMwEJa1s%3D; existShop=MTU4OTUxMzg4Ng%3D%3D; cookie2=127c31851b600a7bc98a14ae3fbfaa35; sg=%E5%91%809b; cna=e/xEF8vueXYCAXgk/tJOk4yu; skt=be7d6f6a68bdf21b; _tb_token_=f3537395e97e6; dnk=%5Cu5468%5Cu5468%5Cu5468%5Cu5A77%5Cu5440; uc1=cookie14=UoTUM2U4He9x4w%3D%3D&cookie16=Vq8l%2BKCLySLZMFWHxqs8fwqnEw%3D%3D&existShop=false&cookie21=U%2BGCWk%2F7p4mBoUyS4E9C&cookie15=UtASsssmOIJ0bQ%3D%3D&pas=0; everywhere_tool_welcome=true; uc3=lg2=VFC%2FuZ9ayeYq2g%3D%3D&vt3=F8dBxGZrX56zbyJvoXA%3D&id2=UUBYgbP%2Fj3plJg%3D%3D&nk2=tZeg5DYKdklryA%3D%3D; tracknick=%5Cu5468%5Cu5468%5Cu5468%5Cu5A77%5Cu5440; uc4=nk4=0%40tyORzivMizi0rl2wUboLaWM1Rcyr&id4=0%40U2LK%2FAlRTu7HbKtNWQnmQZOW3075; unb=2805422229; tfstk=ciB5BesRj405qgXr3wZ2THiC-bpFa5NXD7TVVsca0vuEZYIWksXSQFtqq60jHCKf.; _samesite_flag_=true; l=eBOe4PkqQC-BObPsBOfZlurza77OSIRYGuPzaNbMiOCP_pCM5KCfBZbFkcTHC3hch6vHR3fmgkfgBeYBqQAonxvOYkp9ZQDmn; _cc_=WqG3DMC9EA%3D%3D; cookie17=UUBYgbP%2Fj3plJg%3D%3D; _nk_=%5Cu5468%5Cu5468%5Cu5468%5Cu5A77%5Cu5440; sgcookie=E0J2dz0gcDsHZI6M6FzNy; t=1f43e16350fc4feadf353d8da075fb45; v=0; csg=f4cfd4f9; isg=BCYmihj1RA9iHxCrTqZxQkOZd5yoB2rBwsrSTRDPEskkk8ateJe60Qxh7o4fQ2LZ";
        TbResponse tbResponse = orderQuery(cookies, "995105379792700878");
        System.out.println(tbResponse);
    }
}
